Skip to main content

First-Class Function

When function is treated like a variable, we can say that it is a first-class function. A first-class function can either return a function, or accept a function or both accept and return a function.

Example

var print = function () {
console.log("Hello World");
};

print(); // Invoke function using a variable

We are assigning anonymous function to a variable print, then we use that variable to invoke the function by adding parentheses after the variable.

Accept a function as an argument

function sum(a, b) {
return a + b;
}
function add(fn) {
console.log("Sum is " + fn(2, 3));
}
add(sum);

We are passing sum() function as an argument to the function add() function.

Note

The function that we pass as an argument to another function is called callback function. Here, sum() function is a callback function.

Return a function

Using a variable

Example

function sum(a, b) {
return function () {
console.log("Sum is " + (a + b));
};
}

var result = sum(7, 5);
result();

Here, we are using a variable to invoke the function. At first invoke the function sum() returns the function itself without invoking returned function. In the second invoke the returned function is invoked.

Using double parentheses

Example

function sum(a, b) {
return function () {
console.log("Sum is " + (a + b));
};
}

sum(7, 5)();

We can also use double parentheses to invoke returned function.

Assign or return two functions

function sum(a, b) {
return a + b;
}
function mul(a, b) {
return a * b;
}
function result(fn1, fn2) {
console.log("Sum is " + fn1(2, 3));
console.log("Multiply is " + fn2(3, 4));
}
result(sum, mul);

Here there are two callback functions, sum and mul.